﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace MvcStudy.Areas.Admin.Controllers
{
    [CheckIP]
    public class BaseController : Controller
    {
        /// <summary>
        /// Ip白名单
        /// </summary>
        public static Dictionary<string, string> IpWhiteDic = new Dictionary<string, string>();

        static BaseController()
        {
            //示例，从TXT文本文档读取白名单IP，实际情况应从数据库中读取
            string[] whiteIpList = System.IO.File.ReadAllLines(string.Join("/", AppDomain.CurrentDomain.BaseDirectory, "App_Data", "IPWhite.txt"));
            foreach (var ip in whiteIpList)
            {
                IpWhiteDic.Add(ip, null);
            }
        }        
    }

    /// <summary>
    /// 限制IP
    /// </summary>
    public class CheckIP : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.ActionName != "BAIMINGDANG")
            {
                if (BaseController.IpWhiteDic.ContainsKey(System.Web.HttpContext.Current.Request.UserHostAddress) || System.Web.HttpContext.Current.Request.UserHostAddress.Contains("211.151.97.") || System.Web.HttpContext.Current.Request.UserHostAddress.Contains("211.151.98."))
                {
                    return;
                }
                filterContext.Result = new HomeController().InvalidIp();
            }
        }
    }
}
